//
//  FileDownloadManager.m
//  dataGathering
//
//  Created by macmini on 15/3/28.
//  Copyright (c) 2015年 shuili. All rights reserved.
//

#import "FileDownloadManager.h"
#import "LatestLayerModelManager.h"

@implementation FileDownloadManager

+(void)downloadTPKFile:(NSString *)tpkName
                      :(NSProgress*)progress
               success:(void (^)())success
               failure:(void (^)(NSError *error))failure
{
    NSFileManager* fm=[NSFileManager defaultManager];
    NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [appDocumentPath stringByAppendingString:@"/TPK"];
    
    if (![fm fileExistsAtPath:filePath]) {
        NSLog(@"there is no Directory: %@",filePath);
        [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *toDownloadURL;
    NSString *toDownloadName;
    for(MapGroupModel *mModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] map] groups])
    {
        for(MapLayerModel *mlModel in [mModel layers])
        {
            if([[mlModel name] isEqualToString:tpkName])
            {
                toDownloadURL = [mlModel download_url];
                toDownloadName = [mlModel name];
                break;
            }
        }
    }
    
    toDownloadURL = [@"http://218.94.6.92:8033/slxc.server/" stringByAppendingString:toDownloadURL];
    
    
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:toDownloadURL]];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
        
        NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString* tpkDirectoryPath = [appDocumentPath stringByAppendingPathComponent:@"/TPK/"];
        
        NSString *finaPath = [[tpkDirectoryPath stringByAppendingPathComponent:toDownloadName] stringByAppendingString:@".tpk"];
        
        NSURL *downloadURL =  [NSURL fileURLWithPath:finaPath isDirectory:NO];
        
        return downloadURL;
        
    } completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error) {

        success();
    }];
    
    [downloadTask resume];
    
}

@end
